package com.uraurora.crescent.util;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

public class Concurrents {

    private static final int TIMEOUT_SECONDS = 60;

    private Concurrents(){}

    public static void shutdownAndAwaitTermination(ExecutorService pool, Consumer<? super ExecutorService> action) {
        pool.shutdown(); // Disable new tasks from being submitted
        try {
            // Wait a while for existing tasks to terminate
            if (!pool.awaitTermination(TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
                pool.shutdownNow(); // Cancel currently executing tasks
                // Wait a while for tasks to respond to being cancelled
                if (!pool.awaitTermination(TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
                    action.accept(pool);
                }
            }
        } catch (InterruptedException ie) {
            // (Re-)Cancel if current thread also interrupted
            pool.shutdownNow();
            // Preserve interrupt status
            Thread.currentThread().interrupt();
        }
    }

    public static void shutdownAndAwaitTermination(ExecutorService pool) {
        shutdownAndAwaitTermination(pool, p->System.err.println("Pool did not terminate"));
    }

}
